package com.qing.demo.netty.server;

import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.EmptyByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;


/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {
//   当客户端主动链接后，这个通道就是活跃的，可以发送数据给客户端
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel=(SocketChannel)ctx.channel();
        System.out.println("链接报告开始");
        System.out.println("链接报告信息：有一个客户端链接到本地服务器");
        System.out.println("链接报告IP:"+ socketChannel.localAddress().getHostString());
        System.out.println("链接报告端口:"+ socketChannel.localAddress().getPort());
        System.out.println("链接报告结束");
    }

    /**
     * 当客户端主动断开服务器连接后，这个通道就是不活跃的，不可以传递数据
     * @param ctx
     * @throws Exception
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开链接");
    }

    // 异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof java.net.SocketException && "Connection reset".equals(cause.getMessage())) {
            System.out.println("连接被客户端重置");
            // 记录日志，执行清理工作
        } else {
            // 其他异常处理
            cause.printStackTrace();
        }
        // 关闭连接
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       if(msg instanceof HttpRequest){
           DefaultHttpRequest request=(DefaultHttpRequest)msg;
           System.out.println("URI:"+request.uri());
           System.out.println(msg);
       }
       if(msg instanceof HttpContent){
           LastHttpContent httpContent=(LastHttpContent)msg;
           ByteBuf byteData=httpContent.content();
           if(!(byteData instanceof EmptyByteBuf)){
               byte[] msgByte=new byte[byteData.readableBytes()];
               byteData.readBytes(msgByte);
               System.out.println(new String(msgByte, Charset.forName("utf-8")));
           }
       }

       String sendMsg="<h1>孔子穷乎陈</h1>、蔡之间，藜羹不斟，七日不食，昼寝。<br/>" +
               "颜回索米，得而炊之。几熟，孔子望见颜回攫其甑中而食之。</br/>" +
               "少时，食熟，谒孔子而进食。孔子佯为不见之，曰：“今者吾梦见先君，食洁而后馈。”<br/>" +
               "颜回对曰：“不可！向者尘入甑中，弃之不祥，吾攫而食之。”<br/>" +
               "孔子叹曰：“所信者目也，而目犹不可信；所恃者心也，而心犹不足恃。弟子志之，知人固不易也！";
        FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(sendMsg.getBytes(Charset.forName("utf-8"))));
        HttpHeaders headers=response.headers();
        headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8");
        headers.set(HttpHeaderNames.CONTENT_LENGTH,String.valueOf(response.content().readableBytes()));
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }

}
